import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-05-06
 * Time: 15:20
 */
public class PriorityQueue {
    public int[] elem;
    public int usedSize;

    public PriorityQueue() {
        this.elem = new int[8];
        this.usedSize = 0;
    }

    /**
     * 建堆的时间复杂度：O(n)
     *
     * @param array
     */
    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
        for (int i = (usedSize - 1 - 1) / 2; i >= 0; i--) {
            siftDown(i, usedSize);
        }
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void siftDown(int root,int len) {
        int child = root * 2 + 1;
        while(child < len) {
            if(child + 1 < len && elem[child] < elem[child + 1]) {
                child++;
            }
            if(elem[root] < elem[child]) {
                swap(root, child);
                root = child;
                child = root * 2 + 1;
            } else {
                break;
            }

        }
    }
    private  void swap(int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem, elem.length * 2);
        }
        elem[usedSize++] = val;
        siftUp(usedSize - 1);
    }

    private void siftUp(int child) {
        int parent = (child - 1) / 2;
        while(child > 0) {
            if(elem[child] > elem[parent]) {
                swap(child, parent);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                return;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        swap(0, --usedSize);
        siftDown(0, usedSize);
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if (isEmpty()) {
            return -1;
        }
        return elem[0];
    }

    public static void main(String[] args) {
        PriorityQueue priorityQueue = new PriorityQueue();
        int[] arr = new int[]{5, 91, 6, 9, 20, 1, 43, 6};
        priorityQueue.createHeap(arr);
        System.out.println(Arrays.toString(priorityQueue.elem));
        priorityQueue.push(55);
        System.out.println(Arrays.toString(priorityQueue.elem));
        priorityQueue.pollHeap();
        System.out.println(Arrays.toString(priorityQueue.elem));
        System.out.println(priorityQueue.peekHeap());
    }

}
